package com.zlll.winner.service.lhtUser;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zlll.winner.business.model.lhtUser.LhtUserAddress;
import com.zlll.winner.enums.CommonEnum;
import com.zlll.winner.mapper.lhtUser.LhtUserAddressMapper;
import com.zlll.winner.business.service.lhtUser.ILhtUserAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 收货地址 服务实现类
 * </p>
 *
 * @author qsx
 * @since 2019-09-26
 */
@Service
public class LhtUserAddressServiceImpl extends ServiceImpl<LhtUserAddressMapper, LhtUserAddress> implements ILhtUserAddressService {

    @Autowired
    private LhtUserAddressMapper mapper;

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public Boolean saveLhtUserAddress(LhtUserAddress address) {
        Long time = System.currentTimeMillis();
        if (address.getIsDefault().equals(CommonEnum.YesOrNo.YES.val())) {
            setNotDefault(address.getUserId(),time);
        }
        address.setCreateTime(time);
        return save(address);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public Boolean updateLhtUserAddress(LhtUserAddress address) {
        Long time = System.currentTimeMillis();
        if (address.getIsDefault().equals(CommonEnum.YesOrNo.YES.val())) {
            setNotDefault(address.getUserId(),time);
        }
        address.setUpdateTime(time);
        return updateById(address);
    }


    /**
     * 设置默认
     * @param userId
     * @param time
     */
    public void setNotDefault(Long userId,Long time){
        LambdaQueryWrapper<LhtUserAddress> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(LhtUserAddress::getIsDel, CommonEnum.DelEnum.UNDEL.val());
        wrapper.eq(LhtUserAddress::getUserId, userId);
        wrapper.eq(LhtUserAddress::getIsDefault, CommonEnum.YesOrNo.YES.val());
        List<LhtUserAddress> lhtUserAddressList = mapper.selectList(wrapper);
        for (LhtUserAddress lhtUserAddress : lhtUserAddressList) {
            lhtUserAddress.setIsDefault(CommonEnum.YesOrNo.NO.val());
            lhtUserAddress.setUpdateTime(time);
        }
        if (lhtUserAddressList.size() > 0) {
            updateBatchById(lhtUserAddressList);
        }
    }

    @Override
    public List<LhtUserAddress> getLhtUserAddressList(Long userId) {
        LambdaQueryWrapper<LhtUserAddress> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(LhtUserAddress::getIsDel, CommonEnum.DelEnum.UNDEL.val());
        wrapper.eq(LhtUserAddress::getUserId, userId);
        return mapper.selectList(wrapper);
    }
}
